package me.illtamer.infinite.util;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class FileUtil {

    /**
     * 获取文件内容
     * @return 返回以 UTF-8 编码的一段字符串
     * */
    @NotNull
    public static String getFileContent(@NotNull File file) {
        try (
                FileReader reader = new FileReader(file);
        ) {
            String encoding = reader.getEncoding();
            int len;
            char[] chars = new char[1024];
            StringBuilder builder = new StringBuilder();
            while ((len = reader.read(chars)) != -1)
                builder.append(chars, 0, len);
            if ("UTF8".equals(encoding) || "UTF-8".equals(encoding))
                return builder.toString();
            else
                return new String(builder.toString().getBytes(encoding), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("Some error occurred when getting file({}) content !", file, e);
        }
        return "";
    }

}
